#include "whitespacewatermarkgenerator.h"

namespace Wishmaster
{
	WhitespaceWatermarkGenerator::WhitespaceWatermarkGenerator()
	{
	}

	WhitespaceWatermarkGenerator::~WhitespaceWatermarkGenerator()
	{
	}

	QString WhitespaceWatermarkGenerator::id()
	{
		return QString("whitespace");
	}

	TextWatermarkGeneratorPtr WhitespaceWatermarkGenerator::clone()
	{
		return TextWatermarkGeneratorPtr(new WhitespaceWatermarkGenerator());
	}

	QString WhitespaceWatermarkGenerator::cast(const QString& input, const QByteArray& watermark)
	{
		return input + convert(watermark);
	}

	QString WhitespaceWatermarkGenerator::convert(const QByteArray& watermark)
	{
		if(watermark.isEmpty())
			return QString();
		QString result;
		result.append(QChar(Boundary));
		for(int i = 0; i < watermark.length(); i++)
		{
			unsigned char c = (unsigned char)watermark.at(i);
			encodePart(c, result);
			c >>= 2;
			encodePart(c, result);
			c >>= 2;
			encodePart(c, result);
			c >>= 2;
			encodePart(c, result);
		}
		result.append(QChar(Boundary));
		return result;
	}

	bool WhitespaceWatermarkGenerator::probe(const QString& input)
	{
		if(input.contains(QChar(Boundary)))
			return true;
		return false;
	}

	QByteArray WhitespaceWatermarkGenerator::decode(const QString& input)
	{
		int index = input.indexOf(Boundary);
		if(index < 0)
			return QByteArray();
		QByteArray result;
		unsigned char b = 0;
		int cnt = 0;
		for(int i = index + 1; i < input.length(); i++)
		{
			unsigned short c = input.at(i).unicode();
			if(c == Boundary)
				return result;

			if(c >= Base || c < Base + 4)
				b |= ((c - Base) << (cnt * 2));
			else
				return QByteArray();

			if(cnt == 3)
			{
				result.append(b);
				b = 0;
				cnt = 0;
			}
			else
				cnt++;

		}
		return QByteArray(); // If execution reached here, then the watermark isn't closed
	}

	void WhitespaceWatermarkGenerator::encodePart(unsigned char part, QString& output)
	{
		int code = part & 0x03;
		output.append(QChar(Base + code));
	}
}
